package com.jsmtr.rms.service.impl;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jsmtr.rms.dao.DaoService;
import com.jsmtr.rms.entity.CMSContent;
import com.jsmtr.rms.entity.CMSNode;
import com.jsmtr.rms.service.ICMSService;
import com.jsmtr.rms.utils.BeanTools;

@Service
public class CMSService implements ICMSService {

    @Resource
    private DaoService dao;

    public void setDao(DaoService dao) {
        this.dao = dao;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CMSNode> getNodes() throws Exception {
        return dao.find("from CMSNode order by ordernum");
    }

    @Override
    public CMSNode getNode(String id) throws Exception {
        return (CMSNode) dao.findUnique("from CMSNode where id='" + id + "'");
    }

    @Override
    public CMSContent getContent(String id) throws Exception {
        return (CMSContent) dao.findUnique("from CMSContent where id='" + id + "'");
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CMSContent> getContents(String[] ids) throws Exception {
        return dao.find("from CMSContent where id in(:idlist)", ids);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CMSContent> getContents(List<String> nids) throws Exception {
        return dao.find("from CMSContent where nodeid not in(:idlist)", nids);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CMSContent> getContents(String nid) throws Exception {
        return dao.find("from CMSContent where nodeid='" + nid + "'");
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getResults(int page, int perpage, CMSContent cont) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuffer queryHQL = new StringBuffer("from CMSContent r where 1=1 ");
        StringBuffer countHQL = new StringBuffer("select count(*) from CMSContent r where 1=1 ");
        StringBuffer condition = new StringBuffer();

        condition.append(BeanTools.hqlWhere(cont, "r"));

        condition.append(" order by r.addtime desc");

        queryHQL.append(condition);
        countHQL.append(condition);
        double count = ((Long) dao.findUnique(countHQL.toString())).doubleValue();
        double pageCount = Math.ceil(count / (double) perpage);

        List<CMSContent> list = dao.findLimit(queryHQL.toString(), perpage * (page - 1), perpage);

        map.put("pageCount", pageCount);
        map.put("count", count);
        map.put("list", list);
        return map;
    }
}
